/*
 * Copyright 2013 JROSE
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.jrose.core.jdbc.datasource;

import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@NoArgsConstructor
public class RoutingDataSource extends AbstractRoutingDataSource {
    private final List<Object> slaveLookupKeys = new LinkedList<>();
    private final AtomicInteger pollingIndex = new AtomicInteger(0);

    @Override
    public void setTargetDataSources(Map<Object, Object> targetDataSources) {
        super.setTargetDataSources(targetDataSources);
        this.slaveLookupKeys.addAll(targetDataSources.keySet());
    }

    @Override
    protected Object determineCurrentLookupKey() {
        if (slaveLookupKeys.isEmpty()) {
            return null;
        }
        RoutingPolicy policy = CurrentRoutingPolicy.current();
        switch (policy) {
            case usingMaster: {
                return null;
            }
            case usingSlave: {
                if (slaveLookupKeys.size() == 1) {
                    return slaveLookupKeys.get(0);
                }
                synchronized (slaveLookupKeys) {
                    int index = this.pollingIndex.getAndIncrement();
                    if (index == slaveLookupKeys.size() - 1) {
                        this.pollingIndex.set(0);
                    }
                    return slaveLookupKeys.get(index);
                }
            }
            default: {
                throw new IllegalStateException();
            }
        }
    }
}
